<template>
  <div class="space-y-6">
    <n-card title="个人信息" size="large">
      <div class="flex items-start space-x-8">
        <!-- 头像 -->
        <div>
          <img :src="avatar || '@/assets/naivelogo.svg'" alt="avatar" class="w-40 h-40 rounded-full" />
        </div>

        <!-- 用户信息 -->
        <div class="space-y-3 flex-1">
          <div class="grid grid-cols-3 gap-4">
            <div>
              <p class="text-gray-500">登录账号</p>
              <p class="font-medium">{{ loginName }}</p>
            </div>

            <!-- 昵称 -->
            <div>
              <p class="text-gray-500">昵称</p>
              <div class="flex items-center">
                <template v-if="!isEditing">
                  <p class="font-medium text-sm mr-2">{{ nickName }}</p>
                  <n-button text size="small" @click="startEdit">
                    <template #icon>
                      <Icon icon="mdi:pencil" width="18" height="18" />
                    </template>
                  </n-button>
                </template>
                <template v-else>
                  <div class="flex items-center gap-2">
                    <n-input v-model:value="editedNickName" style="width: 180px" />
                    <n-button type="primary" circle @click="saveNickName">
                      <template #icon>
                        <Icon icon="mdi:check" width="18" height="18" />
                      </template>
                    </n-button>
                    <n-button type="error" circle @click="isEditing = false">
                      <template #icon>
                        <Icon icon="mdi:close" width="18" height="18" />
                      </template>
                    </n-button>
                  </div>
                </template>
              </div>
            </div>

            <div>
              <p class="text-gray-500">邮箱</p>
              <p class="font-medium text-sm">{{ email }}</p>
            </div>
            <div>
              <p class="text-gray-500">手机号</p>
              <p class="font-medium text-sm">{{ phone }}</p>
            </div>
            <div>
              <p class="text-gray-500">更新时间</p>
              <p class="font-medium text-sm">{{ updateTime }}</p>
            </div>
          </div>

          <n-button type="primary" dashed @click="showPasswordDialog = true">修改密码</n-button>
        </div>
      </div>
    </n-card>

    <!-- 修改密码弹窗 -->
    <n-modal v-model:show="showPasswordDialog" preset="dialog" title="修改密码">
      <n-form ref="formRef" :model="passwordForm" :rules="rules" label-placement="left" label-width="100">
        <n-form-item label="旧密码" path="oldPassword">
          <n-input v-model:value="passwordForm.oldPassword" type="password" show-password-on="click" />
        </n-form-item>
        <n-form-item label="新密码" path="newPassword">
          <n-input v-model:value="passwordForm.newPassword" type="password" show-password-on="click" />
        </n-form-item>
        <n-form-item label="确认密码" path="confirmPassword">
          <n-input v-model:value="passwordForm.confirmPassword" type="password" show-password-on="click" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space justify="end">
          <n-button @click="showPasswordDialog = false">取消</n-button>
          <n-button type="primary" @click="handleChangePassword">确认修改</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Icon } from '@iconify/vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/user'
import request from '@/utils/request'
import { ApiEndpoints } from '@/utils/api'

const userStore = useUserStore()
const { loginName, nickName, email, phone, updateTime, avatar } = storeToRefs(userStore)

const isEditing = ref(false)
const editedNickName = ref('')
const showPasswordDialog = ref(false)

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const formRef = ref()
const rules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string) => {
        if (value !== passwordForm.value.newPassword) {
          return new Error('两次输入密码不一致')
        }
        return true
      },
      trigger: 'blur'
    }
  ]
}

const startEdit = () => {
  editedNickName.value = nickName.value || ''
  isEditing.value = true
}

const saveNickName = async () => {
  if (!editedNickName.value) {
    window.$message.error('昵称不能为空')
    return
  }
  const result = await userStore.updateUserInfo(editedNickName.value)
  if (result.success) {
    window.$message.success('保存成功')
    isEditing.value = false
  } else {
    window.$message.error(result.message)
  }
}

const handleChangePassword = async () => {
  await formRef.value?.validate()
  const res = await request.post(ApiEndpoints.USER.changePassword, {
    id: userStore.userId,
    oldPassword: passwordForm.value.oldPassword,
    newPassword: passwordForm.value.newPassword
  })
  if (res.code === 200) {
    window.$message.success('密码修改成功')
    showPasswordDialog.value = false
    passwordForm.value = { oldPassword: '', newPassword: '', confirmPassword: '' }
  } else {
    window.$message.error(res.msg || '密码修改失败')
  }
}
</script>
